//
//  HttpRequest.m
//  Inforcollection
//
//  Created by macbook on 15/12/3.
//  Copyright © 2015年 oceansoft.liw. All rights reserved.
//

#import "HttpRequest.h"

@implementation HttpRequest

+(instancetype)shareRequest
{
    static HttpRequest *httprequest = nil;
    
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        httprequest = [[HttpRequest alloc] initWithBaseURL:[NSURL URLWithString:BaseUrl]];
        httprequest.requestSerializer.timeoutInterval = 50;
        AFJSONRequestSerializer *ser = [AFJSONRequestSerializer serializer];
        [ser setValue:@"application/json;charset=utf-8;text/html" forHTTPHeaderField:@"Content-Type"];
        httprequest.requestSerializer = ser;
        httprequest.responseSerializer.acceptableContentTypes =[NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",@"text/plain",nil];
    });
    return httprequest;
}

-(AFHTTPRequestOperation *)getJsonWithUrl:(NSString *)url WithParameters:(NSDictionary *)parameters complete:(void(^)(id receivedData,NSError *error))complete
{
    return [self GET:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        NSError *error = nil;
        
        complete(responseObject,error);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        complete(nil,error);
        
        [MBProgressHUD showHUDAddedTo:SharedApplication.keyWindow text:@"网络错误" duration:1.5 whileExecutingBlock:^{
            
        }];
    }];
}

- (AFHTTPRequestOperation *)fetchJSONForURLString:(NSString *)URLString
                                       Parameters:(NSDictionary *)parameters
                                       completion:(void (^)(id receivedData, NSError *error))completion
{
    self.requestSerializer.timeoutInterval = 15;
    return [self POST:URLString
           parameters:parameters
              success:^(AFHTTPRequestOperation *task, id responseObject) {
                  dispatch_async(dispatch_get_main_queue(), ^{
                      [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
                      NSError *error = nil;
                      completion(responseObject,error);
                  });
              } failure:^(AFHTTPRequestOperation *task, NSError *error) {
                  dispatch_async(dispatch_get_main_queue(), ^{
                      [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
                      completion(nil, error);
                      [MBProgressHUD showHUDAddedTo:SharedApplication.keyWindow text:@"网络错误" duration:1.5 whileExecutingBlock:^{
                          
                      }];
                  });
                  
              }];
}

@end
